/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufc.stopwatchplugin.panel;

import java.util.Calendar;
import java.util.TimerTask;
import javax.swing.JButton;

/**
 *
 * @author nelson
 */
public class Chronometer extends TimerTask {

    private Calendar calendar;
    private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("HH:mm:ss");
    private JButton btn;
    
    /**
     * The constructor
     * @param btn 
     * @param initialCalendar
     */
    public Chronometer(JButton btn, Calendar initialCalendar) {
        this.btn = btn;
        if(initialCalendar == null)
        {
            this.calendar = Calendar.getInstance();
            clear();
        }
        else
        {
            this.calendar = initialCalendar;
        }
    }

    public Calendar getCalendar() {
        return calendar;
    }

    private void clear() {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    @Override
    public void run() {

        if (StopwatchBtn.isCount()) {

            calendar.add(Calendar.SECOND, 1);
        }

        if (StopwatchBtn.isReset()) {
            clear();
            StopwatchBtn.setReset(false);
        }
        
        btn.setText(timerFormat.format(calendar.getTime()));
    }
}
